package com.cyou.qb.common.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.cyou.nad.datastore.DataList;
import com.cyou.nad.datastore.query.JdbcPage;
import com.cyou.nad.datastore.query.JdbcPageDao;
import com.cyou.qb.common.dao.AwardDao;
import com.cyou.qb.common.dao.AwardDetailDao;
import com.cyou.qb.common.dao.JiuGongGeDao;
import com.cyou.qb.common.dao.WinnerDao;
import com.cyou.qb.common.domain.Award;
import com.cyou.qb.common.domain.AwardDetail;
import com.cyou.qb.common.domain.FrontAward;
import com.cyou.qb.common.domain.JiuGongGe;
import com.cyou.qb.common.service.AwardService;
import com.cyou.qb.exception.ServiceException;

@Service("AwardServiceImpl")
public class AwardServiceImpl extends BaseSerivceImpl implements AwardService {

	@Autowired
	private AwardDao awardDao;

	@Autowired
	private AwardDetailDao awardDetailDao;

	@Autowired
	private JdbcPageDao jdbcPageDao;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private WinnerDao winnerDao;

	@Autowired
	private JiuGongGeDao jiuGongGeDao;

	@Override
	public List<Award> findAwards(int activeId) {
		return awardDao.findAwardsByActiveId(activeId);
	}

	public Award findAward(int awardId) {
		return awardDao.findAwardById(awardId);
	}

	public void updateAwardCurrNum(Award award) {
		awardDao.updateAwardCurrNum(award);
	}

	/**
	 * Description 删除一样奖品,同时删除在九宫格中的数据
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-9-23 下午10:02:44
	 * @see TODOsome class
	 */
	@Override
	public int removeAward(String awardId) throws Exception {
		Award award = awardDao.findAwardById(Integer.valueOf(awardId));//先获取active，然后进行set
		if (award != null) {
			//首先判断是否已经有中奖数据
			boolean chekD = winnerDao.checkDrawAward(award.getActiveId(), award.getId());
			if (chekD) {
				throw new ServiceException("已经存在中奖数据，此奖品不能被删除");
			} else {
				award.setValid(0);
				awardDao.updateOneAward(award);
				getServiceContext().addLog(award.getName(), award.getId(), "t_award", "删除一样奖品", new Object[] { 0 },
						new Object[] { 1 });
				//同时删除九宫格数据库中数据
				jiuGongGeDao.deleteJiuGongGeByAwardId(Integer.valueOf(awardId));
				getServiceContext().addLog("删除的九宫格", award.getId(), "t_jiu_gong_ge", "删除一样奖品,同时删除他的九宫格数据", null,
						new Object[] { jiuGongGeDao.findJIuGongGeByAwardId(Integer.valueOf(awardId)) });
			}
		} else {
			throw new ServiceException("数据库出错，找不到活动");
		}
		return 0;
	}

	@Override
	public AwardDetail findAwardDetail(int awardId) {
		return awardDetailDao.findOneAwardDetailByAwardId(awardId);
	}

	public void setAwardDao(AwardDao awardDao) {
		this.awardDao = awardDao;
	}

	/**
	 * Description 添加一个新奖品
	 * @author lidongwei
	 * @since 2012-10-9 上午11:56:40
	 * @see TODOsome class
	 */
	@Override
	public int saveOneAward(String awardNmae, String type, String minitype, String useAdd, String memo,
			String awardImageUrl, int adminId, String activityId) {
		Award award = new Award();
		award.setActiveId(Integer.valueOf(activityId));
		award.setName(awardNmae);
		award.setType(type);
		award.setChannel(minitype);
		award.setImage(awardImageUrl);
		award.setUrl(useAdd);
		award.setMemo(memo);
		award.setValid(1);
		award.setCreateDate(new Date());
		awardDao.saveOneAward(award);
		getServiceContext().addLog(award.getName(), award.getId(), "t_award", "删除一样奖品", new Object[] { award }, null);
		return 0;
	}

	/**
	 * Description
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-9 下午6:20:17
	 * @see TODOsome class
	 */
	@Override
	public void updateOnewAward(String awardId, String awardName, String type, String minitype, String useAdd,
			String memo, String awardImageUrl, int adminId) throws Exception {
		Award award = awardDao.findAwardById(Integer.valueOf(awardId));//先获取active，然后进行set
		if (award != null) {
			Award oldAw = award;
			award.setName(awardName);
			award.setType(type);
			award.setChannel(minitype);
			award.setUrl(useAdd);
			award.setImage(awardImageUrl);
			award.setMemo(memo);

			awardDao.updateOneAward(award);
			getServiceContext().addLog(award.getName(), award.getId(), "t_award", "修改一样奖品", new Object[] { award },
					new Object[] { oldAw });
		} else {
			throw new ServiceException("数据库出错，找不到奖品");
		}
		//需要填写log日志

	}

	/**
	 * Description 分页查询
	 * @author lidongwei
	 * @since 2012-10-9 下午7:38:21
	 * @see TODOsome class
	 */
	@Override
	public JdbcPage pageQueryAward(String activeId, int pageNo, int pageSize) {
		String sql = "select id,name,type,channel,image,url,max_num as maxNum,curr_num as currNum,g_num as gNum,memo,win_type as winType,num_win as numWin,date_win as dateWin,valid,create_date as createDate "
				+ " from t_award " + " where active_id=? and valid=1 order by  create_date desc";
		List<Object> param = new ArrayList<Object>();
		param.add(Integer.valueOf(activeId));
		return jdbcPageDao.pageQuery(sql, pageNo, pageSize, param.toArray());
	}

	/**
	 * Description
	 * @author lidongwei
	 * @since 2012-10-9 下午8:36:43
	 * @see TODOsome class
	 */
	@Override
	public int findSurplusGb(String awardId) {
		String sql = "select (active.g_max - sumGb.num)" + " as surplusGb" + " from" + " (select "
				+ " (case   when   SUM(max_num*g_num)   is   null      then  0  else  SUM(max_num*g_num)  end ) as num"
				+ " from   t_award a  where a.active_id=" + " (select aa.active_id from t_award aa where aa.id=?)"
				+ " and a.type=3" + " ) as sumGb, t_active active,t_award award "
				+ " where  award.id = ? and award.active_id  = active.id and award.valid=1 and active.status!=0";
		List<Object> param = new ArrayList<Object>(2);
		param.add(Integer.valueOf(awardId));
		param.add(Integer.valueOf(awardId));
		DataList dataList = jdbcPageDao.query(sql, param.toArray());
		if (dataList != null && dataList.rowCount() > 0) {
			return dataList.getInt(0, 0);
		}
		return 0;
	}

	@Override
	public int findActiveMaxAwardNum(int activeId) {
		String sql = "SELECT sum(max_num) from t_award where active_id=?";
		int count = jdbcTemplate.queryForInt(sql, new Object[] { activeId });
		return count;
	}

	/**
	 * Description 实物奖品入库
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-10 下午2:02:44
	 * @see TODOsome class
	 */
	@Override
	public void updateStoreEntity(String awardId, String awardNum) throws Exception {
		Award award = awardDao.findAwardById(Integer.valueOf(awardId));
		if (award != null) {
			long all = (long) Integer.valueOf(awardNum) + (long) award.getMaxNum();
			if (all > 2147483647) {
				throw new ServiceException("累计实物奖品入库数超过2147483647");
			} else {
				Award oldAw = award;
				award.setMaxNum(Integer.valueOf(awardNum) + award.getMaxNum());
				award.setCurrNum(Integer.valueOf(awardNum) + award.getCurrNum());
				awardDao.updateOneAward(award);
				getServiceContext().addLog(award.getName(), award.getId(), "t_award", "实物奖品入库", new Object[] { award },
						new Object[] { oldAw });
			}
		} else {
			throw new ServiceException("数据库出错，找不到奖品");
		}

	}

	/**
	 * Description  经验值入库
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-10 下午4:06:10
	 * @see TODOsome class
	 */
	@Override
	public void updateStoreExperience(String awardId, String experienceNum, String experienceAmount) throws Exception {
		Award award = awardDao.findAwardById(Integer.valueOf(awardId));
		if (award != null) {
			long all = (long) Integer.valueOf(experienceNum) + (long) award.getMaxNum();
			if (all > 2147483647) {
				throw new ServiceException("累计实物奖品入库数超过2147483647");
			} else {
				Award oldAw = award;
				award.setMaxNum(Integer.valueOf(experienceNum) + award.getMaxNum());
				award.setCurrNum(Integer.valueOf(experienceNum) + award.getCurrNum());
				award.setgNum(Integer.valueOf(experienceAmount));
				awardDao.updateOneAward(award);
				getServiceContext().addLog(award.getName(), award.getId(), "t_award", "经验奖品入库", new Object[] { award },
						new Object[] { oldAw });
			}
		} else {
			throw new ServiceException("数据库出错，找不到奖品");
		}
	}

	/**
	 * Description gb入库
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-10 下午4:33:36
	 * @see TODOsome class
	 */
	@Override
	public void updateStoreGb(String awardId, String gbnum, String gbAmount) throws Exception {
		Award award = awardDao.findAwardById(Integer.valueOf(awardId));
		if (award != null) {
			int surplusGb = this.findSurplusGb(awardId);
			if (surplusGb >= Integer.valueOf(gbnum) * Integer.valueOf(gbAmount)) {
				Award oldAw = award;
				award.setMaxNum(Integer.valueOf(gbnum) + award.getMaxNum());
				award.setCurrNum(Integer.valueOf(gbnum) + award.getCurrNum());
				award.setgNum(Integer.valueOf(gbAmount));
				awardDao.updateOneAward(award);
				getServiceContext().addLog(award.getName(), award.getId(), "t_award", "g币入库", new Object[] { award },
						new Object[] { oldAw });
			} else {
				throw new ServiceException("G币数量大于可用G币数量");
			}
		} else {
			throw new ServiceException("数据库出错，找不到奖品");
		}

	}

	/**
	 * Description
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-10 下午6:18:00
	 * @see TODOsome class
	 */
	@Override
	public int saveAwardDetails(String[] txtArray, String awardId) throws Exception {
		List<AwardDetail> awardDetails = new ArrayList<AwardDetail>();
		for (int i = 0; i < txtArray.length; i++) {
			AwardDetail awardDetail = new AwardDetail();
			String oneDeail[] = txtArray[i].split(",");
			if (oneDeail[0].length() > 40) {
				throw new ServiceException("卡号过长");
			} else {
				awardDetail.setCardNo(oneDeail[0]);
				if (oneDeail.length >= 2) {
					if (oneDeail[1].length() > 40) {
						throw new ServiceException("密码过长");
					} else {
						awardDetail.setCardPwd(oneDeail[1]);
					}
				}
				awardDetail.setAwardId(Integer.valueOf(awardId));
				awardDetail.setCreateDate(new Date());
				awardDetails.add(awardDetail);
			}
		}
		Award award = awardDao.findAwardById(Integer.valueOf(awardId));
		if (award != null) {
			long all = (long) Integer.valueOf(txtArray.length) + (long) award.getMaxNum();
			if (all > 2147483647) {
				throw new ServiceException("累计虚拟奖品入库数超过2147483647");
			} else {
				Award oldAw = award;
				award.setMaxNum(txtArray.length + award.getMaxNum());
				award.setCurrNum(txtArray.length + award.getCurrNum());
				awardDao.updateOneAward(award);
				getServiceContext().addLog(award.getName(), award.getId(), "t_award", "虚拟奖品入库", new Object[] { award },
						new Object[] { oldAw });
				awardDetailDao.saveAwardDetials(awardDetails, awardId);
				getServiceContext().addLog(awardDetails.getClass().toString(), awardDetails.size(), "t_award_detail",
						"虚拟奖品入库,一个list，多个awardDetail", new Object[] { awardDetails }, null);
			}
		} else {
			throw new ServiceException("数据库出错，找不到奖品");
		}

		return 0;
	}

	/**
	 * Description
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-11 下午10:26:22
	 * @see TODOsome class
	 */
	@Override
	public int findCurrNum(String awardId) throws Exception {

		Award award = awardDao.findAwardById(Integer.valueOf(awardId));
		if (award != null) {

			return award.getCurrNum();
		} else {
			throw new ServiceException("数据库出错，找不到奖品");
		}
	}

	/**
	 * Description 根据activeId获取相应的奖品
	 * @author lidongwei
	 * @since 2012-10-13 下午4:06:15
	 * @see TODOsome class
	 */
	@Override
	public DataList findAwardsByActId(String activeId) {
		/**
		 * select aw.id,aw.active_id as activeId,aw.name,aw.type,aw.channel,aw.image,aw.url,aw.max_num as maxNum,
		aw.curr_num as currNum,aw.g_num as gNum,aw.memo,aw.win_type as winType,aw.num_win as numWin,aw.date_win as dateWin,
		aw.valid,aw.create_date as createDate,(case   when   condis.position   is   null      then  -1  else  condis.position  end ) as position 
		 from t_award aw 
		LEFT  JOIN
		(select id,active_id as activeId,award_id as awardId , position,create_date as createDate from t_jiu_gong_ge where active_id=29) as condis
		ON condis.awardId=aw.id
		where aw.active_id=29 and aw.valid=1 
		 */

		String sql = "select aw.id,aw.name,aw.type,aw.channel,aw.image,aw.url,aw.max_num as maxNum,"
				+ " aw.curr_num as currNum,aw.g_num as gNum,aw.memo,aw.win_type as winType,aw.num_win as numWin,aw.date_win as dateWin,"
				+ " aw.valid,aw.create_date as createDate,(case   when   condis.position   is   null      then  -1  else  condis.position  end ) as position"
				+ " from t_award aw " + " LEFT  JOIN"
				+ " (select award_id as awardId , position from t_jiu_gong_ge where active_id=?) as condis"
				+ " ON condis.awardId=aw.id" + " where aw.active_id=? and aw.valid=1 ";

		List<Object> param = new ArrayList<Object>();
		param.add(Integer.valueOf(activeId));
		param.add(Integer.valueOf(activeId));
		DataList awardList = jdbcPageDao.query(sql, param.toArray());

		return awardList;
	}

	/**
	 * Description 追加奖品
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-15 下午7:33:21
	 * @see TODOsome class
	 */
	@Override
	public void updateAddToAward(String awardId, String addToNum) throws Exception {
		Award award = awardDao.findAwardById(Integer.valueOf(awardId));
		if (award != null) {
			long all = (long) Integer.valueOf(addToNum) + (long) award.getMaxNum();
			if (all > 2147483647) {
				throw new ServiceException("累计奖品入库数超过2147483647");
			} else {
				Award oldAw = award;
				if (award.getType().equals("3")) {//是Gb需要判断库存
					int surplusGb = this.findSurplusGb(awardId);
					if (surplusGb >= Integer.valueOf(addToNum) * award.getgNum()) {
						award.setMaxNum(Integer.valueOf(addToNum) + award.getMaxNum());
						award.setCurrNum(Integer.valueOf(addToNum) + award.getCurrNum());
						awardDao.updateOneAward(award);
					} else {
						throw new ServiceException("G币数量大于可用G币数量");
					}
				} else {
					award.setMaxNum(Integer.valueOf(addToNum) + award.getMaxNum());
					award.setCurrNum(Integer.valueOf(addToNum) + award.getCurrNum());
					awardDao.updateOneAward(award);
				}
				getServiceContext().addLog(award.getName(), award.getId(), "t_award", "追加奖品", new Object[] { award },
						new Object[] { oldAw });
			}
		} else {
			throw new ServiceException("数据库出错，找不到奖品");
		}

	}

	/**
	 * Description
	 * @author lidongwei
	 * @since 2012-10-16 上午10:39:20
	 * @see TODOsome class
	 */
	@Override
	public JdbcPage pageQueryEntity(String awardId, String userNick, String userId, int pageNo, int pageSize) {
		String sql = "select aw.id,aw.name,aw.curr_num currNum, win.passport,win.nickname,win.win_time winTime"
				+ " from t_award aw ,t_winner win "
				+ " LEFT JOIN"
				+ " (select winc.real_name realName,winc.qq,winc.phone,winc.address_code addressCode,winc.province,winc.city,winc.address ,winc.winner_id id"
				+ " from t_winner_contract winc) w" + " ON w.id = win.id" + " where aw.id=?  and win.award_id=? ";

		List<Object> param = new ArrayList<Object>();
		param.add(Integer.valueOf(awardId));
		param.add(Integer.valueOf(awardId));
		if (StringUtils.isNotBlank(userNick)) {
			sql += " and win.nickname like ? ";
			param.add("%" + userNick + "%");
		}
		if (StringUtils.isNotBlank(userId)) {
			sql += " and win.u_center_id = ? ";
			param.add(userId);
		}
		return jdbcPageDao.pageQuery(sql, pageNo, pageSize, param.toArray());
	}

	/**
	 * Description
	 * @author lidongwei
	 * @since 2012-10-16 上午11:52:36
	 * @see TODOsome class
	 */
	@Override
	public JdbcPage pageQueryVirtual(String awardId, String vUserNick, String vUserId, String vWin, int pageNo,
			int pageSize) {

		List<Object> param = new ArrayList<Object>();
		String sql = "";
		//未发出
		if (StringUtils.isNotBlank(vWin) && vWin.equals("1")) {
			if (StringUtils.isNotBlank(vUserNick) || StringUtils.isNotBlank(vUserId)) {
				return new JdbcPage();
			}
			sql = "select aw.id awid,awd.id wadid,awd.card_no cardNo,awd.card_pwd cardPwd ,'' as WinTime  from t_award aw ,t_award_detail awd "
					+ " where aw.id=? and awd.award_id=aw.id and  NOT EXISTS "
					+ " (select aw.id awid,awd.id wadid,awd.card_no cardNo,awd.card_pwd cardPwd from t_award aw1 ,t_award_detail awd1 , t_winner win1"
					+ " where aw1.id=? and awd1.award_id=aw1.id and win1.award_detail_id = awd1.id and awd1.id=awd.id)";
			param.add(Integer.valueOf(awardId));
			param.add(Integer.valueOf(awardId));
		} else {
			//已发出和所有
			sql = "select aw.id awid ,awd.id awdid ,awd.card_no cardNo,awd.card_pwd cardPwd ,win.passport ,win.nickname,win.win_time winTime from t_award aw ,t_award_detail awd";
			if (StringUtils.isNotBlank(vWin) && vWin.equals("0")) {
				sql += " RIGHT JOIN";
			} else {
				sql += " LEFT JOIN";
			}
			sql += " (SELECT * from t_winner where award_id=?";
			param.add(Integer.valueOf(awardId));
			sql += ") win" + " ON win.award_detail_id = awd.id" + " where aw.id=? and awd.award_id=aw.id ";
			param.add(Integer.valueOf(awardId));
			if (StringUtils.isNotBlank(vUserNick)) {
				sql += " and win.nickname like ? ";
				param.add("%" + vUserNick + "%");
			}
			if (StringUtils.isNotBlank(vUserId)) {
				sql += " and win.u_center_id = ? ";
				param.add(vUserId);
			}
		}

		return jdbcPageDao.pageQuery(sql, pageNo, pageSize, param.toArray());
	}

	/**
	 * Description
	 * @author lidongwei
	 * @since 2012-10-16 下午1:07:46
	 * @see TODOsome class
	 */
	@Override
	public JdbcPage pageQueryGBAndExp(String awardId, String userNick, String userId, int pageNo, int pageSize) {
		String sql = " select aw.id awid,aw.name , aw.curr_num currNum,win.passport,win.nickname,win.win_time winTime from t_award aw ,t_winner win"
				+ " where aw.id=?  and win.award_id=?";

		List<Object> param = new ArrayList<Object>();
		param.add(Integer.valueOf(awardId));
		param.add(Integer.valueOf(awardId));

		if (StringUtils.isNotBlank(userNick)) {
			sql += " and win.nickname like ? ";
			param.add("%" + userNick + "%");
		}
		if (StringUtils.isNotBlank(userNick)) {
			sql += " and win.u_center_id = ? ";
			param.add(userId);
		}
		return jdbcPageDao.pageQuery(sql, pageNo, pageSize, param.toArray());
	}

	/**
	 * Description
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-16 下午7:31:16
	 * @see TODOsome class
	 */
	@Override
	public void updateNoVirNum(String awardId, String newCurrNum) throws Exception {

		Award award = awardDao.findAwardById(Integer.valueOf(awardId));
		if (award != null) {
			long all = (long) Integer.valueOf(newCurrNum) - (long) award.getCurrNum() + (long) award.getMaxNum();
			if (all > 2147483647) {
				throw new ServiceException("累计奖品入库数超过2147483647");
			} else {
				if (Integer.valueOf(newCurrNum) >= 0) {
					Award oldAw = award;
					award.setMaxNum(Integer.valueOf(newCurrNum) - award.getCurrNum() + award.getMaxNum());
					award.setCurrNum(Integer.valueOf(newCurrNum));
					awardDao.updateOneAward(award);
					getServiceContext().addLog(award.getName(), award.getId(), "t_award", "修改非虚拟奖品的数量",
							new Object[] { award }, new Object[] { oldAw });
				} else {
					throw new ServiceException("请输入大于等于0的整数");
				}
			}
		} else {
			throw new ServiceException("数据库出错，找不到奖品");
		}
	}

	/**
	 * Description 删除虚拟奖品
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-16 下午8:47:17
	 * @see TODOsome class
	 */
	@Override
	public void removeVirtual(List<String> virtualIdList, String awardId) throws Exception {

		Award award = awardDao.findAwardById(Integer.valueOf(awardId));

		if (award != null) {
			int num = 0;
			if (virtualIdList != null && virtualIdList.size() > 0) {
				for (int i = 0; i < virtualIdList.size(); i++) {
					Integer virtualId = Integer.valueOf(virtualIdList.get(i));
					int winnerCount = winnerDao.getWinnerCountByVirId(virtualId);
					if (winnerCount < 1) {
						getServiceContext().addLog(award.getName(), virtualId, "t_award_detail", "删除虚拟奖品", null,
								new Object[] { awardDetailDao.findAwardDetailById(virtualId) });
						awardDetailDao.removeVirtualById(virtualId);
						num++;
					}
				}
				if (num <= award.getCurrNum()) {
					Award oldAw = award;
					award.setCurrNum(award.getCurrNum() - num);
					award.setMaxNum(award.getMaxNum() - num);
					awardDao.updateOneAward(award);
					getServiceContext().addLog(award.getName(), award.getId(), "t_award", "删除虚拟奖品",
							new Object[] { award }, new Object[] { oldAw });
				} else {
					throw new ServiceException("获取虚拟奖品删除个数出错");
				}
			}

		} else {
			throw new ServiceException("数据库出错，找不到奖品");
		}

	}

	@Override
	public List<FrontAward> findAwardList() throws Exception {
		List<FrontAward> list = awardDao.findAwardList();
		return list;
	}

	@Override
	public int updateOneAwardDetail(AwardDetail awardDetail) throws Exception {
		int count = awardDetailDao.updateOneAwardDetail(awardDetail);
		if (count == 0)
			throw new ServiceException("更新奖品明细记录失败");
		return count;
	}

	/**
	 * Description
	 * @author lidongwei
	 * @since 2012-10-30 上午10:42:21
	 * @see TODOsome class
	 */
	@Override
	public List<Integer> findNumWinListByActId(String activeId) {
		String sql = "select num_win" + " from t_award" + " where active_id=" + activeId
				+ " and win_type=3 and valid=1 and num_win >= -1 ";
		return jdbcTemplate.queryForList(sql, Integer.class);
	}

}
